<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>08.custom_binding | KnockOut</title>
  <script src="../assets/knockout-3.5.1.js"></script>
</head>
<body>

  <div data-bind="withProperties: { displayMode: 'twoColumn' }">
    外部的显示方式是 <span data-bind="text: displayMode"></span>.
    <div data-bind="withProperties: { displayMode: 'doubleWidth' }">
      内部的显示方式是 <span data-bind="text: displayMode"></span>, 仍然能访问外部的显示方式 <span data-bind="text: $parentContext.displayMode"></span>.
    </div>
  </div>

  <script type="text/javascript">
    ko.bindingHandlers.withProperties = {
      init: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
        // 创建一个具有额外属性的修改绑定上下文，并将其应用于后代元素
        var childBindingContext = bindingContext.createChildContext(
          bindingContext.$rawData, 
          null, // 可选, 在此传递一个字符串作为后代上下文中数据项的别名
          function(context) {
            ko.utils.extend(context, valueAccessor());
        });
        ko.applyBindingsToDescendants(childBindingContext, element);

        // 还要告诉 KO *不要* 绑定后代本身，否则它们将被绑定两次
        return { controlsDescendantBindings: true };
      }
    };

    var vm = {}

    ko.applyBindings(vm);
  </script>

</body>
</html>